﻿using Approval.Domain;
using AutoMapper;
using MediatR;
using PublicCommon;
using T_Person.APi.Applation.CommandHandlers.PersonnelHandlers;
using T_Person.BaseRep.Interface;
using T_Person.Domain;

namespace T_Person.APi.Applation.Commands.PersonnelCommand
{
    public class PersonnelAddCommand : IRequestHandler<PersonnelAddHandlers, int>
    {
        private readonly IMapper _mapper;
        private readonly IPersonnelRep personnelRep;
        private readonly IEmployeeRep employeeRep;
        private readonly Cross_services_Helper cross_Services_Helper;

        public PersonnelAddCommand(IPersonnelRep personnelRep, IMapper mapper, IEmployeeRep employeeRep, Cross_services_Helper cross_Services_Helper)
        {
            this.personnelRep = personnelRep;
            _mapper = mapper;
            this.employeeRep = employeeRep;
            this.cross_Services_Helper = cross_Services_Helper;
        }

        public async Task<int> Handle(PersonnelAddHandlers request, CancellationToken cancellationToken)
        {
            request.FiledDate = DateTime.Now;
            request.CreateDate = DateTime.Now;
            request.CreateBy = "小明";
            var list = _mapper.Map<Personnel>(request);
            var list2 = await personnelRep.GetAloneByresult(x => x.EmployeeId == list.EmployeeId && x.RLZId == list.RLZId&&!x.IsDel);
            if (list2 != null && list2.AuditState != 3)
            {
                return await Task.FromResult(-2);
            }
            var list3 = await employeeRep.GetAloneByresult(x => x.Ename == list.EmployeeId);
            if (list3 != null && string.IsNullOrEmpty(list3.EntrtDate.ToString()))
            {
                list3.EntrtDate = list.EntryDate;
                list3.UpdateDate = DateTime.Now;
                list3.UpdateBy = "小红";
                await employeeRep.Update(list3);
            }
            await personnelRep.Add(list);
            if (list.AuditState>0)
            {
                list3.AuditState=list.AuditState;
                list3.EmployeeStyle++;
                await employeeRep.Update(list3);
            }
            var obj = new RLZRelation();
            obj.RLZId = list.Id.ToString();
            obj.ApprovalId = 4;
            obj.ApprovalName = "小明";
            var message = await cross_Services_Helper.Post("http://10.31.60.9:8000/Approval/api/RLZRelation/RLZRelationAdd", obj);
            if (Convert.ToInt32(message) < 0)
            {
                return await Task.FromResult(-1);
            }
            return await Task.FromResult(list.Id);
        }
    }
}
